import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
Vue.use(Router)
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Home.vue')
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ '@/components/Welcome.vue')
const Test = () => import(/* webpackChunkName: "user_info" */ '@/views/Test.vue')
const NotFound = () => import(/* webpackChunkName: "user_info" */ '@/components/NotFound.vue')

const ruleMapping = {
  test: Test
}
const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome, meta: { name: '欢迎' } },
        { path: '/test', component: Test, meta: { name: '测试' } }
      ]
    },
    {
      path: '*',
      component: NotFound
    }
  ]
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next()  放行    next('/login')  强制跳转

  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

// 动态加载路由权限
export function initDynamicRoutes() {
  // 根据二级权限对路由规则进行动态添加
  const currentRoutes = router.options.routes
  const rightList = store.store.rightList
  rightList.forEach(item => {
    item.children.forEach(item => {
      // item二级权限
      const temp = ruleMapping[item.path]
      currentRoutes[2].children.push(temp)
    })
  })
  router.addRoute(currentRoutes)
}

export default router
